package com.jfinal.club._admin.student;

import java.util.List;
import com.jfinal.club.common.model.Student;
import com.jfinal.kit.Ret;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;

public class StudentAdminService {

	private Student dao = new Student().dao();
	
	public Page<Student> paginate(int pageNum) {
		return dao.paginate(pageNum, 10, "select student.id,student.sname,banji.clname,account.nickName ", "from student left join banji on student.clid=banji.id left join account on student.userid=account.id order by student.id desc");
	}
	
	public boolean exists(int studentId, String name) {
		name = name.toLowerCase().trim();
		String sql = "select id from student where sname = ? and id != ? limit 1";
		Integer id = Db.queryInt(sql, name, studentId);
		return id != null;
	}
	
	public List<Student> getAll() {
		List<Student> list = dao.find("select * from student order by sname");
		return list;
	}
	
	public Ret save(int id, Student student) {
//		area.setId(id);
		student.setSname(student.getSname().trim());
		student.save();
		return Ret.ok("msg", "创建成功");
	}
	
	public Student edit(int id) {
		return dao.findById(id);
	}
	
	public Ret update(Student student) {
		if (exists(student.getId(), student.getSname())) {
			return Ret.fail("msg", "学生已经存在");
		}

		student.setSname(student.getSname().trim());
		student.update();
		return Ret.ok("msg", "修改成功");
	}
	
	public Ret delete(int studentId) {
		dao.deleteById(studentId);
		return Ret.ok("msg", "学生删除成功");
	}
}
